import numpy as np
from itertools import product
from clothing_data_model import Outfit
import random


class OutfitGenerator:
    def __init__(self, content_recommender, items_catalog):
        """
        初始化搭配生成器

        参数:
            content_recommender: 基于内容的推荐器实例
            items_catalog: 所有服装项的列表
        """
        self.content_recommender = content_recommender
        self.items_catalog = items_catalog
        self.outfit_templates = self._create_outfit_templates()

        # 增强的颜色搭配规则
        self.color_harmony_rules = self._create_color_harmony_rules()

        # 场景适应性映射
        self.scene_clothing_map = self._create_scene_clothing_map()

        # 温度适应性映射
        self.temperature_clothing_map = self._create_temperature_clothing_map()

    def _create_outfit_templates(self):
        """创建搭配模板"""
        templates = [
            # 基础模板：上衣+裤子+鞋子
            {"上衣": ["毛衣", "衬衣", "短袖", "长袖", "外套", "西装外套", "卫衣", "长羽绒服", "短羽绒服", "大衣", "冲锋衣"], "裤子": 1, "鞋子": 1},

            # 带其他配件的基础模板
            {"上衣": ["毛衣", "衬衣", "短袖", "长袖", "外套", "西装外套", "卫衣", "长羽绒服", "短羽绒服", "大衣", "冲锋衣"], "裤子": 1, "鞋子": 1, "其他": 1},

            # 裙装模板
            {"上衣": ["毛衣", "衬衣", "短袖", "长袖", "外套", "西装外套", "卫衣", "长羽绒服", "短羽绒服", "大衣", "冲锋衣"], "裙子": 1, "鞋子": 1},

            # 带其他配件的裙装模板
            {"上衣": ["毛衣", "衬衣", "短袖", "长袖", "外套", "西装外套", "卫衣", "长羽绒服", "短羽绒服", "大衣", "冲锋衣"], "裙子": 1, "鞋子": 1, "其他": 1},

            # 多层上衣模板 - 冬季
            {"上衣": [["毛衣", "长袖", "短袖", "衬衣"], ["外套", "西装外套", "长羽绒服", "短羽绒服", "大衣", "冲锋衣"]], "裤子": 1, "鞋子": 1},

            # 多层上衣+配件模板 - 冬季
            {"上衣": [["毛衣", "长袖", "短袖", "衬衣"], ["外套", "西装外套", "长羽绒服", "短羽绒服", "大衣", "冲锋衣"]], "裤子": 1, "鞋子": 1, "其他": 1},

            # 多层上衣模板 - 冬季裙装
            {"上衣": [["毛衣", "长袖", "短袖", "衬衣"], ["外套", "西装外套", "长羽绒服", "短羽绒服", "大衣", "冲锋衣"]], "裙子": 1, "鞋子": 1},

            # 多层上衣+配件模板 - 冬季裙装
            {"上衣": [["毛衣", "长袖", "短袖", "衬衣"], ["外套", "西装外套", "长羽绒服", "短羽绒服", "大衣", "冲锋衣"]], "裙子": 1, "鞋子": 1, "其他": 1},

            # 夏季模板
            {"上衣": ["短袖", "吊带"], "裤子": ["短裤", "休闲裤", "牛仔裤"], "鞋子": 1},

            # 夏季裙装模板
            {"上衣": ["短袖", "吊带"], "裙子": ["短裙", "半身裙"], "鞋子": 1},
        ]
        return templates

    def _create_color_harmony_rules(self):
        """创建增强的颜色搭配规则"""
        # 基础颜色组
        neutral_colors = ["黑色", "白色", "灰色", "米色", "卡其色", "棕色", "藏青色"]
        warm_colors = ["红色", "橙色", "黄色", "粉色", "珊瑚色", "桃红色"]
        cool_colors = ["蓝色", "绿色", "紫色", "薄荷色", "天蓝色", "湖蓝色"]

        # 颜色和谐规则
        harmony_rules = {
            # 单色系：同一颜色的不同深浅
            "monochromatic": {
                "黑色": ["深灰色", "灰色", "浅灰色"],
                "蓝色": ["深蓝色", "天蓝色", "浅蓝色"],
                "红色": ["深红色", "酒红色", "粉色"],
                # 其他颜色的单色系...
            },

            # 互补色：色轮上相对的颜色
            "complementary": {
                "红色": ["绿色"],
                "蓝色": ["橙色"],
                "黄色": ["紫色"],
                # 其他互补色...
            },

            # 三色组：色轮上均匀分布的三种颜色
            "triadic": [
                ["红色", "黄色", "蓝色"],
                ["橙色", "绿色", "紫色"],
                # 其他三色组...
            ],

            # 中性色与任何颜色都能搭配
            "neutral_with_any": {
                color: warm_colors + cool_colors for color in neutral_colors
            },

            # 暖色系组合
            "warm_palette": [warm_colors],

            # 冷色系组合
            "cool_palette": [cool_colors],
        }

        # 扩展互补色规则
        for color, complements in list(harmony_rules["complementary"].items()):
            for complement in complements:
                if complement not in harmony_rules["complementary"]:
                    harmony_rules["complementary"][complement] = [color]
                else:
                    harmony_rules["complementary"][complement].append(color)

        # 扩展中性色规则
        for neutral in neutral_colors:
            for color_group in [warm_colors, cool_colors]:
                for color in color_group:
                    if color not in harmony_rules["neutral_with_any"]:
                        harmony_rules["neutral_with_any"][color] = [neutral]
                    else:
                        harmony_rules["neutral_with_any"][color].append(neutral)

        return harmony_rules

    def _create_scene_clothing_map(self):
        """创建场景与服装的映射关系"""
        scene_map = {
            "日常": {
                "上衣": ["短袖", "卫衣", "长袖", "毛衣"],
                "裤子": ["牛仔裤", "休闲裤", "运动裤",'工装裤','背带裤'],
                "裙子": ["半身裙","长裙"],
                "鞋子": ["运动鞋", "板鞋", "布鞋"],
                "其他": ["帽子", "围巾","包包"]
            },
            "通勤": {
                "上衣": ["衬衣", "毛衣", "长袖", "外套"],
                "裤子": ["西裤", "休闲裤", "牛仔裤"],
                "裙子": ["半身裙", "连衣裙"],
                "鞋子": ["皮鞋", "布鞋", "靴子"],
                "其他": ["围巾","包包"]
            },
            "约会": {
                "上衣": ["衬衣", "毛衣", "外套"],
                "裤子": ["牛仔裤", "休闲裤"],
                "裙子": ["连衣裙", "半身裙"],
                "鞋子": ["皮鞋", "靴子"],
                "其他": ["首饰","包包"]
            },
            "运动": {
                "上衣": ["短袖", "卫衣", "外套"],
                "裤子": ["运动裤", "短裤"],
                "鞋子": ["运动鞋"],
                "其他": ["帽子"]
            },
            "旅行": {
                "上衣": ["短袖", "长袖", "卫衣", "外套"],
                "裤子": ["牛仔裤", "休闲裤", "短裤"],
                "裙子": ["长裙","连衣裙"],
                "鞋子": ["运动鞋", "布鞋"],
                "其他": ["帽子", "围巾"]
            },
            "聚会": {
                "上衣": ["衬衣", "毛衣", "外套"],
                "裤子": ["牛仔裤", "西裤"],
                "裙子": ["连衣裙", "半身裙"],
                "鞋子": ["皮鞋", "靴子","板鞋","高跟鞋"],
                "其他": ["首饰"]
            },
            "正式场合": {
                "上衣": ["衬衣", "西装外套", "大衣"],
                "裤子": ["西裤"],
                "裙子": ["连衣裙"],
                "鞋子": ["皮鞋", "高跟鞋"],
                "其他": ["首饰"]
            }
        }
        return scene_map

    def _create_temperature_clothing_map(self):
        """创建温度与服装的映射关系"""
        temp_map = {
            "极寒": {  # -10°C以下
                "上衣": ["长羽绒服", "毛衣"],
                "裤子": ["加绒裤"],
                "裙子": ["加绒裙"],
                "鞋子": ["保暖鞋", "雪地靴","运动鞋"],
                "其他": ["围巾","帽子"]
            },
            "寒冷": {  # -10°C到5°C
                "上衣": ["长羽绒服", "短羽绒服","大衣", "外套", "毛衣","长袖","冲锋衣"],
                "裤子": ["加绒裤", "牛仔裤", "休闲裤"],
                "裙子": ["加绒裙", "长裙"],
                "鞋子": ["靴子", "保暖鞋"],
                "其他": ["围巾", "帽子"]
            },
            "凉爽": {  # 5°C到15°C
                "上衣": ["外套", "毛衣", "长袖", "衬衣", "卫衣"],
                "裤子": ["牛仔裤", "休闲裤", "西裤"],
                "裙子": ["长裙", "连衣裙", "半身裙"],
                "鞋子": ["皮鞋", "运动鞋", "布鞋", "靴子"],
                "其他": ["围巾", "帽子"]
            },
            "温和": {  # 15°C到22°C
                "上衣": ["长袖", "衬衣", "毛衣", "外套", "卫衣", "短袖"],
                "裤子": ["休闲裤", "牛仔裤", "西裤"],
                "裙子": ["半身裙", "连衣裙", "长裙"],
                "鞋子": ["运动鞋", "皮鞋", "布鞋", "板鞋"],
                "其他": ["围巾"]
            },
            "温暖": {  # 22°C到28°C
                "上衣": ["短袖", "衬衣", "长袖"],
                "裤子": ["休闲裤", "牛仔裤", "短裤"],
                "裙子": ["半身裙", "连衣裙", "短裙","长裙"],
                "鞋子": ["运动鞋", "凉鞋", "布鞋"],
                "其他": ["墨镜", "帽子"]
            },
            "炎热": {  # 28°C以上
                "上衣": ["短袖", "吊带"],
                "裤子": ["短裤"],
                "裙子": ["短裙", "连衣裙","半身裙"],
                "鞋子": ["凉鞋", "板鞋"],
                "其他": ["帽子","墨镜"]
            }
        }
        return temp_map

    def _get_temperature_category(self, temperature):
        """根据温度获取对应的温度类别"""
        if temperature is None:
            return None

        if temperature < -10:
            return "极寒"
        elif temperature < 5:
            return "寒冷"
        elif temperature < 15:
            return "凉爽"
        elif temperature < 22:
            return "温和"
        elif temperature < 28:
            return "温暖"
        else:
            return "炎热"

    def generate_outfits(self, user_profile, context=None, template_idx=None, n_outfits=5):
        """
        生成服装搭配

        参数:
            user_profile: 用户档案
            context: 上下文信息 (可选)
            template_idx: 使用的模板索引 (可选)
            n_outfits: 生成的搭配数量

        返回:
            生成的搭配列表
        """
        # 确保每次调用都有不同的随机性
        random.seed()  # 使用系统时间作为种子
        np.random.seed()  # 重置numpy随机种子

        if template_idx is None:
            # 如果有风格主题，选择合适的模板
            if context and context.style_theme:
                template_idx = self._select_template_by_style(context.style_theme)
            else:
                # 随机选择模板
                template_idx = np.random.randint(0, len(self.outfit_templates))

        template = self.outfit_templates[template_idx]
        outfits = []

        # 尝试生成n_outfits个搭配
        attempts = 0
        max_attempts = n_outfits * 5  # 增加最大尝试次数

        # 获取温度类别（如果有）
        temp_category = None
        if context and hasattr(context, 'temperature') and context.temperature is not None:
            temp_category = self._get_temperature_category(context.temperature)
            print(f"当前温度: {context.temperature}°C, 温度类别: {temp_category}")

        while len(outfits) < n_outfits and attempts < max_attempts:
            attempts += 1

            outfit_items = []
            outfit_id = len(outfits) + random.randint(1000, 9999)  # 使用随机ID增加多样性

            # 用于跟踪每个类别已选择的子类别
            selected_subcategories = {}

            # 温度适应性：如果有温度信息，优先根据温度选择衣物
            temp_filter = None
            if temp_category and temp_category in self.temperature_clothing_map:
                temp_filter = self.temperature_clothing_map[temp_category]
                print(f"应用温度过滤: {temp_category}")

            # 场景适应性：如果有指定场景，优先选择适合该场景的衣物
            scene_filter = None
            if context and hasattr(context, 'scene') and context.scene:
                scene = context.scene
                if scene in self.scene_clothing_map:
                    scene_filter = self.scene_clothing_map[scene]
                    print(f"应用场景过滤: {scene}")

            # 为每个类别推荐衣服
            for category, count_or_subcats in template.items():
                # 处理新的模板格式
                if isinstance(count_or_subcats, list):
                    # 如果是嵌套列表，表示多层上衣
                    if any(isinstance(item, list) for item in count_or_subcats):
                        for layer_subcats in count_or_subcats:
                            # 获取推荐的衣服
                            recommended_items = self.content_recommender.recommend_items(
                                user_profile, category, context, top_n=10)  # 增加推荐数量

                            # 应用子类别过滤
                            filtered_items = [item for item in recommended_items if item.subcategory in layer_subcats]
                            
                            # 应用温度过滤（优先级最高）
                            if temp_filter and category in temp_filter:
                                suitable_subcats = temp_filter[category]
                                temp_filtered_items = [item for item in filtered_items
                                                    if item.subcategory in suitable_subcats]
                                # 如果过滤后还有足够的衣物，使用过滤后的结果
                                if len(temp_filtered_items) >= 1:
                                    filtered_items = temp_filtered_items
                                    print(f"类别 {category} 应用温度过滤后剩余 {len(filtered_items)} 件衣物")
                                elif len(temp_filtered_items) > 0:
                                    filtered_items = temp_filtered_items
                                    print(f"类别 {category} 温度过滤后只有 {len(temp_filtered_items)} 件衣物，但仍优先使用温度过滤结果")
                                else:
                                    print(f"警告: 类别 {category} 温度过滤后没有衣物，使用原始推荐")

                            # 应用场景过滤（优先级次之）
                            if scene_filter and category in scene_filter:
                                suitable_subcats = scene_filter[category]
                                scene_filtered_items = [item for item in filtered_items
                                                        if item.subcategory in suitable_subcats]
                                # 如果过滤后还有足够的衣物，使用过滤后的结果
                                if len(scene_filtered_items) >= 1:
                                    filtered_items = scene_filtered_items
                                    print(f"类别 {category} 应用场景过滤后剩余 {len(filtered_items)} 件衣物")
                                else:
                                    print(f"警告: 类别 {category} 场景过滤后只有 {len(scene_filtered_items)} 件衣物，使用温度过滤后的推荐")

                            # 如果没有足够的推荐项，跳过这次尝试
                            if len(filtered_items) < 1:
                                print(f"警告: 类别 {category} 推荐衣物不足，跳过此次尝试")
                                continue

                            # 随机选择一件符合条件的衣物
                            selected_item = random.choice(filtered_items)
                            outfit_items.append(selected_item)
                    else:
                        # 单层但指定了子类别
                        # 获取推荐的衣服
                        recommended_items = self.content_recommender.recommend_items(
                            user_profile, category, context, top_n=10)  # 增加推荐数量

                        # 应用子类别过滤
                        filtered_items = [item for item in recommended_items if item.subcategory in count_or_subcats]
                        
                        # 应用温度过滤（优先级最高）
                        if temp_filter and category in temp_filter:
                            suitable_subcats = temp_filter[category]
                            temp_filtered_items = [item for item in filtered_items
                                                if item.subcategory in suitable_subcats]
                            # 如果过滤后还有足够的衣物，使用过滤后的结果
                            if len(temp_filtered_items) >= 1:
                                filtered_items = temp_filtered_items
                                print(f"类别 {category} 应用温度过滤后剩余 {len(filtered_items)} 件衣物")
                            elif len(temp_filtered_items) > 0:
                                filtered_items = temp_filtered_items
                                print(f"类别 {category} 温度过滤后只有 {len(temp_filtered_items)} 件衣物，但仍优先使用温度过滤结果")
                            else:
                                print(f"警告: 类别 {category} 温度过滤后没有衣物，使用原始推荐")

                        # 应用场景过滤（优先级次之）
                        if scene_filter and category in scene_filter:
                            suitable_subcats = scene_filter[category]
                            scene_filtered_items = [item for item in filtered_items
                                                    if item.subcategory in suitable_subcats]
                            # 如果过滤后还有足够的衣物，使用过滤后的结果
                            if len(scene_filtered_items) >= 1:
                                filtered_items = scene_filtered_items
                                print(f"类别 {category} 应用场景过滤后剩余 {len(filtered_items)} 件衣物")
                            else:
                                print(f"警告: 类别 {category} 场景过滤后只有 {len(scene_filtered_items)} 件衣物，使用温度过滤后的推荐")

                        # 如果没有足够的推荐项，跳过这次尝试
                        if len(filtered_items) < 1:
                            print(f"警告: 类别 {category} 推荐衣物不足，跳过此次尝试")
                            continue

                        # 随机选择一件符合条件的衣物
                        selected_item = random.choice(filtered_items)
                        outfit_items.append(selected_item)
                else:
                    # 原有的处理逻辑，使用数量
                    count = count_or_subcats
                    # 获取推荐的衣服
                    recommended_items = self.content_recommender.recommend_items(
                        user_profile, category, context, top_n=count * 10)  # 增加推荐数量

                    # 应用温度过滤（优先级最高）
                    if temp_filter and category in temp_filter:
                        suitable_subcats = temp_filter[category]
                        temp_filtered_items = [item for item in recommended_items
                                            if item.subcategory in suitable_subcats]
                        # 如果过滤后还有足够的衣物，使用过滤后的结果
                        if len(temp_filtered_items) >= count:
                            recommended_items = temp_filtered_items
                            print(f"类别 {category} 应用温度过滤后剩余 {len(recommended_items)} 件衣物")
                        elif len(temp_filtered_items) > 0:
                            # 即使不足count件，也尽量使用温度过滤后的结果
                            print(f"类别 {category} 温度过滤后只有 {len(temp_filtered_items)} 件衣物，不足 {count} 件，但仍优先使用温度过滤结果")
                            recommended_items = temp_filtered_items
                        else:
                            print(f"警告: 类别 {category} 温度过滤后没有衣物，使用原始推荐")

                    # 应用场景过滤（优先级次之）
                    if scene_filter and category in scene_filter:
                        suitable_subcats = scene_filter[category]
                        scene_filtered_items = [item for item in recommended_items
                                                if item.subcategory in suitable_subcats]
                        # 如果过滤后还有足够的衣物，使用过滤后的结果
                        if len(scene_filtered_items) >= count:
                            recommended_items = scene_filtered_items
                            print(f"类别 {category} 应用场景过滤后剩余 {len(recommended_items)} 件衣物")
                        else:
                            print(
                                f"警告: 类别 {category} 场景过滤后只有 {len(scene_filtered_items)} 件衣物，不足 {count} 件，使用温度过滤后的推荐")

                    # 如果没有足够的推荐项，跳过这次尝试
                    if len(recommended_items) < count:
                        print(f"警告: 类别 {category} 推荐衣物不足 {count} 件，跳过此次尝试")
                        continue

                    # 如果需要选择多件同一类别的衣物，确保它们的子类别不同
                    if count > 1:
                        # 按子类别分组
                        items_by_subcategory = {}
                        for item in recommended_items:
                            if item.subcategory not in items_by_subcategory:
                                items_by_subcategory[item.subcategory] = []
                            items_by_subcategory[item.subcategory].append(item)

                        # 如果子类别数量不足，跳过这次尝试
                        if len(items_by_subcategory) < count:
                            print(f"警告: 类别 {category} 子类别数量不足 {count}，跳过此次尝试")
                            continue

                        # 随机选择不同的子类别
                        selected_subcats = random.sample(list(items_by_subcategory.keys()), count)

                        # 从每个选定的子类别中随机选择一件衣物
                        selected_items = []
                        for subcat in selected_subcats:
                            selected_items.append(random.choice(items_by_subcategory[subcat]))
                    else:
                        # 对于只需要一件的类别，直接随机选择
                        selected_items = [random.choice(recommended_items)]

                    outfit_items.extend(selected_items)

            # Calculate the expected number of items based on the template
            expected_items = 0
            for value in template.values():
                if isinstance(value, int):
                    expected_items += value
                elif isinstance(value, list):
                    # If it's a list of subcategories, count as 1
                    if not any(isinstance(item, list) for item in value):
                        expected_items += 1
                    # If it's a nested list (for layered outfits), count each layer
                    else:
                        expected_items += len(value)

            # Check if we have all needed items
            if len(outfit_items) == expected_items:
                # 创建搭配对象
                outfit = Outfit(outfit_id, outfit_items)

                # 评估温度适应性（如果有温度信息）
                temp_compatibility = 1.0  # 默认值
                if temp_category:
                    temp_compatibility = self._evaluate_temperature_compatibility(outfit, temp_category)
                    print(f"搭配温度兼容性评分: {temp_compatibility:.2f}")

                # 评估季节兼容性（如果没有温度信息，或作为辅助评分）
                season_compatibility = outfit.get_season_compatibility()
                print(f"搭配季节兼容性评分: {season_compatibility:.2f}")

                # 评估颜色搭配
                color_score = self._evaluate_enhanced_color_matching(outfit)
                print(f"搭配颜色评分: {color_score:.2f}")

                # 确定最终阈值：优先考虑温度适应性
                final_threshold = 0.3  # 默认阈值

                if temp_category:
                    # 如果有温度信息，主要看温度适应性
                    if temp_compatibility > 0.5 and color_score > 0.4:
                        outfits.append(outfit)
                        print(f"搭配 {outfit_id} 通过温度和颜色评估，已添加")
                else:
                    # 如果没有温度信息，看季节适应性
                    if season_compatibility > 0.4 and color_score > 0.4:
                        outfits.append(outfit)
                        print(f"搭配 {outfit_id} 通过季节和颜色评估，已添加")

        # 添加多样性控制
        if len(outfits) > 1:
            # 确保不同搭配之间有足够差异
            diverse_outfits = [outfits[0]]
            for outfit in outfits[1:]:
                # 检查是否与已选搭配有足够差异
                if self._is_diverse_enough(outfit, diverse_outfits):
                    diverse_outfits.append(outfit)
                if len(diverse_outfits) >= n_outfits:
                    break

            return diverse_outfits[:n_outfits]

        return outfits

    def _is_diverse_enough(self, new_outfit, existing_outfits, min_diff=2):
        """检查新搭配与现有搭配是否有足够差异"""
        for existing in existing_outfits:
            # 计算不同属性的数量
            differences = 0
            for new_item in new_outfit.items:
                has_difference = True
                for existing_item in existing.items:
                    if (new_item.category == existing_item.category and
                            new_item.subcategory == existing_item.subcategory):
                        has_difference = False
                        break
                if has_difference:
                    differences += 1

            # 如果差异不够，返回False
            if differences < min_diff:
                return False

        return True

    def _select_template_by_style(self, style_theme):
        """根据风格主题选择合适的模板"""
        style_template_map = {
            # 更新风格与模板的映射关系，使其更加合理
            "正式": [0, 2, 4],  # 基础模板、裙装模板或多层上衣模板
            "通勤": [0, 2, 4, 6],  # 各种基础和多层模板
            "运动": [0, 1],  # 基础模板或带配件的基础模板
            "休闲": [0, 1, 4, 5],  # 基础模板、带配件的基础模板或多层上衣模板
            "甜美": [2, 3, 6, 7],  # 裙装相关模板
            "复古": [1, 3, 5, 7],  # 带配件的模板
            "新中式": [2, 3, 6, 7],  # 裙装相关模板
            "辣妹": [1, 3],  # 带配件的模板
            "古风": [2, 3, 6, 7],  # 裙装相关模板
            "极简": [0, 2],  # 基础模板或裙装模板
            "嘻哈": [1, 5],  # 带配件的模板
            "优雅": [2, 3, 6, 7],  # 裙装相关模板
            "哥特": [1, 5],  # 带配件的模板
            "度假风": [1, 3],  # 带配件的模板
            "学院风": [0, 2, 4, 6]  # 各种基础和多层模板
        }

        if style_theme in style_template_map:
            templates = style_template_map[style_theme]
            return random.choice(templates)

        # 默认随机选择
        return random.randint(0, len(self.outfit_templates) - 1)

    def evaluate_outfit(self, outfit, context=None):
        """
        评估搭配的质量

        参数:
            outfit: 要评估的搭配
            context: 上下文信息 (可选)

        返回:
            搭配评分 (0-1)
        """
        if not outfit.items:
            return 0.0

        score = 0.0

        # 评估温度适应性（如果有温度信息）
        temp_score = 0.5  # 默认中等分数
        if context and hasattr(context, 'temperature') and context.temperature is not None:
            temp_category = self._get_temperature_category(context.temperature)
            if temp_category:
                temp_score = self._evaluate_temperature_compatibility(outfit, temp_category)
                # 温度适应性权重更高
                score += 0.4 * temp_score
            else:
                # 如果没有温度信息，评估季节兼容性
                season_compatibility = outfit.get_season_compatibility()
                score += 0.3 * season_compatibility
        else:
            # 如果没有温度信息，评估季节兼容性
            season_compatibility = outfit.get_season_compatibility()
            score += 0.3 * season_compatibility

        # 评估颜色搭配
        color_score = self._evaluate_enhanced_color_matching(outfit)
        score += 0.3 * color_score

        # 评估风格一致性
        style_score = self._evaluate_style_consistency(outfit)
        score += 0.2 * style_score

        # 如果有上下文，评估与上下文的相关性
        if context:
            context_score = self._evaluate_context_relevance(outfit, context)
            # 结合基础评分和上下文相关性
            score = 0.6 * score + 0.4 * context_score

        return score

    def _evaluate_temperature_compatibility(self, outfit, temp_category):
        """评估搭配与特定温度类别的兼容性"""
        if not temp_category or temp_category not in self.temperature_clothing_map:
            return 0.5  # 默认中等兼容性

        temp_map = self.temperature_clothing_map[temp_category]

        # 计算每件衣物与温度的兼容性
        compatibility_scores = []
        for item in outfit.items:
            if item.category in temp_map and item.subcategory in temp_map[item.category]:
                # 完全匹配
                compatibility_scores.append(1.0)
            else:
                # 检查是否在相邻温度类别中
                adjacent_match = False

                # 定义相邻温度类别
                adjacent_categories = {
                    "极寒": ["寒冷"],
                    "寒冷": ["极寒", "凉爽"],
                    "凉爽": ["寒冷", "温和"],
                    "温和": ["凉爽", "温暖"],
                    "温暖": ["温和", "炎热"],
                    "炎热": ["温暖"]
                }

                if temp_category in adjacent_categories:
                    for adj_category in adjacent_categories[temp_category]:
                        if adj_category in self.temperature_clothing_map:
                            adj_map = self.temperature_clothing_map[adj_category]
                            if item.category in adj_map and item.subcategory in adj_map[item.category]:
                                # 相邻温度类别匹配
                                adjacent_match = True
                                break

                if adjacent_match:
                    compatibility_scores.append(0.5)  # 相邻温度类别给予部分兼容性
                else:
                    compatibility_scores.append(0.1)  # 不匹配

        # 计算平均兼容性分数
        if compatibility_scores:
            return sum(compatibility_scores) / len(compatibility_scores)
        return 0.5  # 默认中等兼容性

    def _evaluate_enhanced_color_matching(self, outfit):
        """评估搭配的增强颜色匹配度"""
        # 获取搭配中的所有颜色
        colors = [item.color for item in outfit.items]

        # 如果只有一种颜色，返回高分
        if len(set(colors)) == 1:
            return 0.95

        # 如果只有两种颜色，检查是否是好的配色
        if len(set(colors)) == 2:
            color1, color2 = set(colors)

            # 检查是否是中性色与其他颜色的搭配
            if color1 in self.color_harmony_rules["neutral_with_any"] and color2 in \
                    self.color_harmony_rules["neutral_with_any"][color1]:
                return 0.9

            # 检查是否是互补色
            if color1 in self.color_harmony_rules["complementary"] and color2 in \
                    self.color_harmony_rules["complementary"][color1]:
                return 0.85

            # 检查是否是单色系
            if color1 in self.color_harmony_rules["monochromatic"] and color2 in \
                    self.color_harmony_rules["monochromatic"][color1]:
                return 0.8

        # 对于三种或更多颜色，计算颜色和谐度
        total_pairs = 0
        harmony_score = 0

        for i in range(len(colors)):
            for j in range(i + 1, len(colors)):
                total_pairs += 1
                color_i = colors[i]
                color_j = colors[j]

                # 检查各种颜色和谐规则
                pair_score = 0

                # 相同颜色
                if color_i == color_j:
                    pair_score = 1.0

                # 中性色与其他颜色
                elif (color_i in self.color_harmony_rules["neutral_with_any"] and
                      color_j in self.color_harmony_rules["neutral_with_any"].get(color_i, [])):
                    pair_score = 0.9

                # 互补色
                elif (color_i in self.color_harmony_rules["complementary"] and
                      color_j in self.color_harmony_rules["complementary"].get(color_i, [])):
                    pair_score = 0.85

                # 单色系
                elif (color_i in self.color_harmony_rules["monochromatic"] and
                      color_j in self.color_harmony_rules["monochromatic"].get(color_i, [])):
                    pair_score = 0.8

                # 检查是否属于同一色系组合
                for palette in self.color_harmony_rules["warm_palette"] + self.color_harmony_rules["cool_palette"]:
                    if color_i in palette and color_j in palette:
                        pair_score = max(pair_score, 0.75)

                # 检查是否属于三色组
                for triad in self.color_harmony_rules["triadic"]:
                    if color_i in triad and color_j in triad:
                        pair_score = max(pair_score, 0.7)

                # 如果没有匹配任何规则，给一个基础分
                if pair_score == 0:
                    pair_score = 0.3

                harmony_score += pair_score

        return harmony_score / total_pairs if total_pairs > 0 else 0.5

    def _evaluate_style_consistency(self, outfit):
        """评估搭配的风格一致性"""
        # 扩展风格分类
        style_categories = {
            "休闲": ["短袖", "卫衣", "牛仔裤", "运动裤", "运动鞋", "短裤","板鞋","休闲裤","背带裤"],
            "正式": ["衬衣", "西裤", "皮鞋", "连衣裙", "西装外套", "大衣","高跟鞋"],
            "运动": ["运动裤", "运动鞋", "短袖", "卫衣", "冲锋衣"],
            "复古": ["衬衣", "长裙", "牛仔裤", "连衣裙"],
            "甜美": ["连衣裙", "半身裙", "长裙" ,"毛衣","首饰","包包"],
            "学院风": ["衬衣", "短裙", "板鞋", "领带"]
        }

        # 计算每种风格的衣服数量
        style_counts = {style: 0 for style in style_categories}

        for item in outfit.items:
            for style, subcats in style_categories.items():
                if item.subcategory in subcats:
                    style_counts[style] += 1

        # 计算风格一致性
        total_items = len(outfit.items)
        if total_items == 0:
            return 0.0

        max_style_count = max(style_counts.values())
        style_consistency = max_style_count / total_items

        # 奖励完全一致的风格
        if max_style_count == total_items:
            style_consistency *= 1.2

        return min(1.0, style_consistency)  # 确保不超过1.0

    def _evaluate_context_relevance(self, outfit, context):
        """评估搭配与上下文的相关性"""
        if not context:
            return 0.5  # 默认中等相关性

        score = 0.0

        # 温度相关性（优先级最高）
        temp_score = 0.5  # 默认中等分数
        if hasattr(context, 'temperature') and context.temperature is not None:
            temp_category = self._get_temperature_category(context.temperature)
            if temp_category:
                temp_score = self._evaluate_temperature_compatibility(outfit, temp_category)

        # 季节相关性 - 增强版（如果没有温度信息，或作为辅助评分）
        season_score = 0.5  # 默认中等分数
        if not hasattr(context, 'temperature') or context.temperature is None:
            current_season = context.get_season()
            season_weights = {
                "完全匹配": 1.0,  # 完全匹配当前季节
                "相邻季节": 0.7,  # 相邻季节（如春季衣物在夏季）
                "四季皆宜": 0.8,  # 四季皆宜的衣物
                "不匹配": 0.2,  # 完全不匹配的季节
            }

            # 季节相邻关系
            adjacent_seasons = {
                "春季": ["夏季", "冬季"],
                "夏季": ["春季", "秋季"],
                "秋季": ["夏季", "冬季"],
                "冬季": ["秋季", "春季"]
            }

            season_scores = []
            for item in outfit.items:
                if item.season == current_season:
                    season_scores.append(season_weights["完全匹配"])
                elif "四季" in item.season:
                    season_scores.append(season_weights["四季皆宜"])
                elif current_season in item.season:  # 处理如"春秋"这样的组合季节
                    season_scores.append(season_weights["完全匹配"])
                elif any(season in item.season for season in adjacent_seasons.get(current_season, [])):
                    season_scores.append(season_weights["相邻季节"])
                else:
                    season_scores.append(season_weights["不匹配"])

            season_score = sum(season_scores) / len(season_scores) if season_scores else 0.5

        # 天气相关性
        weather_score = 0.5  # 默认中等分数
        if hasattr(context, 'weather') and context.weather:
            weather_appropriateness = {
                "晴天": lambda item: 0.8,  # 晴天适合大多数衣物
                "阴天": lambda item: 0.8,  # 阴天也适合大多数衣物
                "雨天": lambda item: 0.9 if item.material not in ["皮革", "丝绸", "纸"] else 0.3,  # 雨天不适合皮革、丝绸
                "雪天": lambda item: 0.9 if item.season in ["冬季", "秋冬"] else 0.2,  # 雪天需要保暖衣物
                "大风": lambda item: 0.8 if item.fit != "宽松" else 0.4,  # 大风天不适合宽松衣物
                "炎热": lambda item: 0.9 if item.season in ["夏季", "春夏"] else 0.3,  # 炎热天气需要夏季衣物
                "寒冷": lambda item: 0.9 if item.season in ["冬季", "秋冬"] else 0.2,  # 寒冷天气需要冬季衣物
            }

            if context.weather in weather_appropriateness:
                weather_scores = [weather_appropriateness[context.weather](item) for item in outfit.items]
                weather_score = sum(weather_scores) / len(weather_scores) if weather_scores else 0.5

        # 场景适应性
        scene_score = 0.5  # 默认中等分数
        if hasattr(context, 'scene') and context.scene:
            scene = context.scene
            if scene in self.scene_clothing_map:
                scene_map = self.scene_clothing_map[scene]
                scene_scores = []

                for item in outfit.items:
                    if item.category in scene_map and item.subcategory in scene_map[item.category]:
                        scene_scores.append(1.0)  # 完全适合该场景
                    else:
                        scene_scores.append(0.3)  # 不太适合该场景

                scene_score = sum(scene_scores) / len(scene_scores) if scene_scores else 0.5

        # 根据是否有温度信息，调整各因素权重
        if hasattr(context, 'temperature') and context.temperature is not None:
            # 温度信息存在，温度权重最高
            score = 0.5 * temp_score + 0.2 * weather_score + 0.3 * scene_score
        else:
            # 温度信息不存在，季节权重较高
            score = 0.4 * season_score + 0.3 * weather_score + 0.3 * scene_score

        return score
